package com.atguigu.tingshu.album.task;

import cn.hutool.core.collection.CollectionUtil;
import com.atguigu.tingshu.album.mapper.TrackInfoMapper;
import com.atguigu.tingshu.album.service.VodService;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.model.album.TrackInfo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

@Slf4j
@Component
public class ReviewTask {

    @Autowired
    private TrackInfoMapper trackInfoMapper;

    @Autowired
    private VodService vodService;

    /**
     * 七个值：秒 分 时 日 月 周 [年]
     */
    @Scheduled(cron = "0/5 * * * * ?")
    public void getReviewTaskResult() {
        log.info("[专辑服务]定时获取审核结果");
        //1.根据状态为审核中 的声音查询出声音ID跟审核任务ID
        LambdaQueryWrapper<TrackInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TrackInfo::getStatus, SystemConstant.TRACK_STATUS_REVIEWING);
        queryWrapper.last("limit 100");
        queryWrapper.orderByAsc(TrackInfo::getId);
        queryWrapper.select(TrackInfo::getId, TrackInfo::getReviewTaskId);
        List<TrackInfo> trackInfoList = trackInfoMapper.selectList(queryWrapper);
        //2.判断是否有审核中的声音记录
        if (CollectionUtil.isNotEmpty(trackInfoList)) {
            //3.根据声音表中审核任务ID 查询 审核结果以及 建议
            for (TrackInfo trackInfo : trackInfoList) {
                String reviewTaskId = trackInfo.getReviewTaskId();
                //4.根据建议更新声音表状态
                String suggest = vodService.getReviewTaskResult(reviewTaskId);
                if(StringUtils.isNotBlank(suggest)){
                    if ("pass".equals(suggest)) {
                        trackInfo.setStatus(SystemConstant.TRACK_STATUS_PASS);
                    } else if ("block".equals(suggest)) {
                        trackInfo.setStatus(SystemConstant.TRACK_STATUS_NO_PASS);
                    } else if ("review".equals(suggest)) {
                        trackInfo.setStatus(SystemConstant.TRACK_STATUS_MANUAL);
                    }
                    trackInfoMapper.updateById(trackInfo);
                }
            }


        }
    }
}
